package com.example.newproject_overseas.model

import android.content.Context
import android.net.ConnectivityManager
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.example.newproject_overseas.MyApplication
import com.example.newproject_overseas.compositionLocal.LocalUserViewModel
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


import java.io.IOException
import java.util.concurrent.TimeUnit

object Network {
    // 文档地址：https://d1fil276lfo9fp.cloudfront.net/app-doc/A4D93F35365745428EA8E6C25CB38DE9#APP%E5%AF%B9%E6%8E%A5%E8%AF%B4%E6%98%8E
    // mock 数据请求 url

    //远程请求
    private const val BASE_URL = "https://app.loanhouse.xyz/"
    //private const val BASE_URL = "http://192.168.2.142:88/shop_api/"

    //AppId
    private const val APP_ID = "8RACTAZO"

    //AES密钥 KEY
    private const val AES_SECRET_KEY = "YNN2BFc8N3DZ5WrN"

    private val retrofit: Retrofit by lazy {
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS) // 设置连接超时时间为10秒
            .readTimeout(30, TimeUnit.SECONDS)    // 设置读取超时时间为30秒
            .retryOnConnectionFailure(true)
            .addInterceptor(TokenInterceptor())
            .addInterceptor(RequestInterceptor())
            .addInterceptor(ResponseInterceptor())
            .build()

        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }


    fun <T> createService(clazz: Class<T>): T{

        return retrofit.create(clazz)
    }

    private class TokenInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            //获得loginUser 对象
            var loginUser = MyApplication.loginVM.localLoginUser.value;

            val originalRequest = chain.request()
            val token = generateToken(MyApplication.gaid_cur, "1.0.0", "1.0.0", MyApplication.aid)
            val request = originalRequest.newBuilder()
                .apply {
                    if (loginUser != null) {
                        header("Auth", loginUser.token)
                    }
                    header("Token", token)
                }
                .build()

            return chain.proceed(request)
        }
    }

    private class RequestInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {

            val originalRequest = chain.request()
            val originalBody = originalRequest.body
            val originalString = if (originalBody?.contentType()?.subtype  == "json"){
                val buffer = Buffer()
                originalBody?.writeTo(buffer)
                buffer.readUtf8().toString()


            }else if (originalBody?.contentType()?.subtype == "x-www-form-urlencoded") {
                val formBody = originalBody as FormBody
                val requestBody = mutableMapOf<String, String>()
                for (i in 0 until formBody.size) {
                    val name = formBody.name(i)
                    val value = formBody.value(i)
                    requestBody[name] = value
                }
                requestBody.toString()
            }else{
                ""
            }



            if (originalBody != null)  {
                val encryptedRequest = CryptUtils.encrypt(AES_SECRET_KEY, originalString)
                val newBody = RequestBody.create(originalBody.contentType(), encryptedRequest.toString())
                   val newRequest = originalRequest.newBuilder()
                    .method(originalRequest.method, newBody)
                    .build()

                return chain.proceed(newRequest)
            }

            return chain.proceed(originalRequest)
        }
    }


    private class ResponseInterceptor : Interceptor{

        override fun intercept(chain: Interceptor.Chain): Response {


            val connectivityManager = MyApplication.appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = connectivityManager.activeNetworkInfo
            if (networkInfo == null || !networkInfo.isConnected) {
                // 在没有网络连接的情况下，返回一个空的 Response 或者其他适当的响应
                return Response.Builder()
                    .request(chain.request())
                    .protocol(Protocol.HTTP_1_1)
                    .code(503) // 使用合适的状态码，503 表示服务不可用
                    .message("No internet connection")
                    .body(ResponseBody.create("text/plain".toMediaTypeOrNull(), ""))
                    .build()


            }

            // 有网络连接，继续执行其他代码
            var response: Response  = chain.proceed(chain.request())
            val responseBody = response.body
            val respStr = responseBody?.string() ?: ""

            responseBody?.close()
            if (respStr.startsWith("{") && respStr.endsWith("}")) {
                val jsonResponse = JSONObject(respStr)
                val status = jsonResponse.optInt("status")
                if (status == 1012){
                    return Response.Builder()
                        .request(chain.request())
                        .protocol(Protocol.HTTP_1_1)
                        .code(1012) // 使用合适的状态码，503 表示服务不可用
                        .message("No internet connection")
                        .body(ResponseBody.create("text/plain".toMediaTypeOrNull(), ""))
                        .build()
                }
            }

            val decryptedResponseBody = CryptUtils.decrypt(AES_SECRET_KEY,respStr)
            return response.newBuilder()
                .body(ResponseBody.create(response.body?.contentType(), decryptedResponseBody.toString()))
                .build()

       }

    }


    private fun generateToken(gaid: String, version: String, rv: String, aid: String): String {
        val tokenData = "{\"GAID\":\"$gaid\",\"VERSION\":\"$version\",\"RV\":\"$rv\",\"AID\":\"${aid}\"}"
        return  APP_ID + CryptUtils.encrypt(AES_SECRET_KEY,tokenData)
    }
}